import CCLog from "../CCLog";
import { SKIN_GROUP_DEFAULT, SKIN_LOADED_DEFAULT, SKIN_PATH_PRE } from "../Common/Constant";
import { CONTENT_LIST } from "../Common/ContentList";
import Helper from "../Common/Helper";
import PlatformSystem from "../Platform/PlatformSystem";
import ArchiveSystem from "./ArchiveSystem";

class SkinSystem {
    private _initTimes: number = 2;

    public skinGroups: string[] = null;
    public skinLoaded: ISkinLoaded = Object.assign({}, SKIN_LOADED_DEFAULT);
    public skinUsing: cc.SpriteFrame[] = null;

    public get skinPath(): string {
        return `${SKIN_PATH_PRE}/${ArchiveSystem.localData.skinGroup}`;
    }

    public async initialize() {
        this._initTimes -= 1;
        if (!this.skinGroups) {
            let infos = cc.resources.getDirWithPath(SKIN_PATH_PRE, cc.SpriteFrame);
            let pathsTmp = infos.map(function (info) {
                let pathSlice = (info.path as string).split('/');
                return pathSlice[1];
            });
            this.skinGroups = [...new Set(pathsTmp)].sort();
            if (!this.skinGroups.includes(ArchiveSystem.localData.skinGroup)) ArchiveSystem.localData.skinGroup = SKIN_GROUP_DEFAULT;
        }
        return new Promise((resolve: Function, reject: Function) => {
            
            cc.resources.loadDir(this.skinPath, cc.SpriteFrame, null, (e: Error, res: cc.SpriteFrame[]) => {

               
                //cc.log("error====",res);
                if (e || res.length === 0) {
                    if (this._initTimes === 0) {
                        PlatformSystem.platform.showToast({
                            title: Helper.getContent(CONTENT_LIST.toast.loadingSkinError),
                            icon: 'none',
                            duration: 3000
                        });
                        let timer = new cc.Component();
                        timer.scheduleOnce(PlatformSystem.platform.exitGame, 3);
                    } else {
                        this.initialize();
                    }
                } else {

                    this.skinLoaded.blockSkin[ArchiveSystem.localData.skinGroup] = res;
                    
                    CCLog.log("this.skinPath=res1=",this.skinLoaded.blockSkin[ArchiveSystem.localData.skinGroup].length)
                    resolve(res);
                }
            });
        });
    }

    public getSkinUsing(): cc.SpriteFrame[] {
        return this.skinLoaded.blockSkin[ArchiveSystem.localData.skinGroup];
    }

    public changSkin(num: string): void {
        // TODO 更换皮肤
       
    }
}

export default new SkinSystem();